<template>
  <div class="list-container">
    <!-- 搜索和操作栏 -->
    <div class="list-header">
      <div class="search-form">
        <div class="search-form-item">
          <label>商品名称</label>
          <el-input
            v-model="searchForm.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-form-item">
          <label>店铺名称</label>
          <el-input
            v-model="searchForm.shopName"
            placeholder="请输入店铺名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-form-item">
          <label>商品类型</label>
          <el-select
            v-model="searchForm.goodType"
            placeholder="请选择商品类型"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </div>
      </div>
      <div class="search-actions">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><RefreshRight /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增商品
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="list-content">
      <div class="list-table" v-loading="loading">
        <div class="table-scroll-wrapper" ref="tableScroll">
          <el-table
            ref="tableRef"
            :data="productList"
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="goodId" label="ID" width="100" align="center" sortable />
            <el-table-column prop="goodPic" label="商品图片" width="100" align="center">
              <template #default="{ row }">
                <el-image
                  v-if="row.goodPic"
                  :src="row.goodPic"
                  fit="cover"
                  style="width: 60px; height: 60px; border-radius: 4px"
                  preview-teleported
                  :preview-src-list="[row.goodPic]"
                />
                <span v-else style="color: #909399">暂无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodName" label="商品名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="shopName" label="店铺名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="stock" label="库存" width="100" align="center" />
            
            <el-table-column prop="goodTypeName" label="商品类型" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="row.goodType === 1 ? '' : 'success'">
                  {{ row.goodTypeName || '未知类型' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="authType" label="审核状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="row.authType === 1 ? 'success' : 'warning'">
                  {{ row.authType === 1 ? '已审核' : '未审核' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="addTime" label="添加时间" width="160" align="center" sortable>
              <template #default="{ row }">
                {{ formatDate(row.addTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="160" align="center" sortable>
              <template #default="{ row }">
                {{ formatDate(row.updateTime) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button type="primary" size="small" @click="handleEdit(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDelete(row)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 水平滑动进度条 -->
        <input
          v-show="showHScroll"
          ref="hSlider"
          class="horizontal-scroll"
          type="range"
          min="0"
          max="100"
          :value="hScrollPercent"
          @input="onSliderInput"
        />
      </div>
    </div>

    <!-- 分页 -->
    <div class="list-footer">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑商品弹窗组件 -->
    <GoodDialog
      v-model:visible="dialogVisible"
      :is-edit="isEdit"
      :good-data="currentGood"
      :loading="submitLoading"
      :category-list="categoryList"
      @success="handleFormSubmit"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, Plus, Delete } from '@element-plus/icons-vue'
import '@/assets/css/table-list.css'
import GoodDialog from '@/components/dialogs/GoodDialog.vue'
import {
  getGoodList,
  getGoodById,
  addGood,
  updateGood,
  deleteGood,
  batchDeleteGoods
} from '@/api/good'
import { getCategoryList } from '@/api/goodCategory'

// 搜索表单
const searchForm = reactive({
  name: '',
  shopName: '',
  goodType: undefined
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 列表数据
const productList = ref([])
const loading = ref(false)
const selectedRows = ref([])
const tableRef = ref()
const categoryList = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const editId = ref(null)
const currentGood = ref(null)

// 水平滚动相关
const tableScroll = ref(null)
const hScrollPercent = ref(0)
const showHScroll = ref(false)

// 格式化日期
const formatDate = (time) => {
  if (!time) return ''
  // 匹配 YYYY-MM-DDTHH:mm:ss 并转换为 YYYY-MM-DD HH:mm:ss
  // 如果后端返回的时间带有 T 和时区信息，直接替换 T 为空格并截取前 19 位
  return time.replace('T', ' ').substring(0, 19)
}

// 获取商品分类
const fetchCategoryList = async () => {
  try {
    const res = await getCategoryList({ page: 1, size: 100 })
    if (res.success) {
      categoryList.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败', error)
  }
}

// 获取商品列表
const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name || undefined,
      shopName: searchForm.shopName || undefined,
      goodType: searchForm.goodType || undefined
    }
    const res = await getGoodList(params)
    if (res.success) {
      productList.value = res.data.data || []
      pagination.total = res.data.total || 0
      setTimeout(() => updateHScroll(), 50)
    } else {
      ElMessage.error(res.msg || '获取商品列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取商品列表异常')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.shopName = ''
  searchForm.goodType = undefined
  pagination.currentPage = 1
  fetchList()
}

// 分页事件
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchList()
}

// 表格多选
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除商品 "${row.goodName}" 吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await deleteGood(row.goodId)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('操作失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) return
  const ids = selectedRows.value.map(item => item.goodId)
  
  ElMessageBox.confirm(`确定批量删除这 ${ids.length} 个商品吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await batchDeleteGoods(ids)
      if (res.success) {
        ElMessage.success('批量删除成功')
        fetchList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('操作失败')
    }
  }).catch(() => {})
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  editId.value = null
  currentGood.value = null // 确保清空，触发子组件重置
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  isEdit.value = true
  editId.value = row.goodId
  try {
    // 先获取详情
    const res = await getGoodById(row.goodId)
    if (res.success && res.data) {
      currentGood.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取商品详情异常')
  }
}

// 提交表单（处理子组件传递的数据）
const handleFormSubmit = async (formData) => {
  submitLoading.value = true
  try {
    const api = isEdit.value ? updateGood : addGood
    const args = isEdit.value ? [editId.value, formData] : [formData]
    
    const res = await api(...args)
    
    if (res.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('操作异常')
  } finally {
    submitLoading.value = false
  }
}

// 水平滚动条逻辑
const updateHScroll = () => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  if (maxScroll > 0) {
    showHScroll.value = true
    hScrollPercent.value = Math.round((el.scrollLeft / maxScroll) * 100)
  } else {
    showHScroll.value = false
    hScrollPercent.value = 0
  }
}

const onTableScroll = () => {
  updateHScroll()
}

const onSliderInput = (e) => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  const percent = Number(e.target.value || 0)
  el.scrollLeft = Math.round((percent / 100) * maxScroll)
  hScrollPercent.value = percent
}

// 生命周期
onMounted(() => {
  fetchCategoryList()
  fetchList()
  setTimeout(() => {
    if (tableScroll.value) {
      tableScroll.value.addEventListener('scroll', onTableScroll, { passive: true })
      updateHScroll()
    }
  }, 100)
  window.addEventListener('resize', updateHScroll)
})

onBeforeUnmount(() => {
  if (tableScroll.value) {
    tableScroll.value.removeEventListener('scroll', onTableScroll)
  }
  window.removeEventListener('resize', updateHScroll)
})
</script>
